import React, { useEffect, useState } from 'react';
import { Button, DatePicker, Space, Select } from 'antd';
import { TjSegmented, TjSelect, useTRState } from '@/pages/ETrade/components';
import moment from 'moment/moment';
import { UploadOutlined } from '#/utils/antdIcons';
import { SEARCH_TYPE, COLIMNSTYPEOPTION, TYPE_OPTIONS } from '../helper';

let targetDate = [null, null];
// 当前日期大于当前月的2号
if (moment().diff(moment().startOf('month'), 'days') > 1) {
  targetDate = [moment().startOf('month'), moment()];
} else {
  targetDate = [
    moment().subtract(1, 'months').startOf('month'),
    moment().subtract(1, 'months').endOf('month'),
  ];
}
const defaultForm = (searchType, stations) => {
  // 默认表单
  return {
    date: searchType === 0 ? targetDate : moment(),
    stationIdList: stations.map(({ value }) => value),
    type: 0,
    columnsType: COLIMNSTYPEOPTION.map((t) => t.label),
    searchType,
  };
};
export const HeaderSearch = ({ stations = [], onExport, fetchData }, ref) => {
  const [state, setState] = useTRState(defaultForm(0, stations));
  const [filterStations, setFilterStations] = useState(stations);

  useEffect(() => {
    moment.updateLocale('zh-cn', {
      week: { dow: 5, doy: 4 },
    });
    defaultRequest();
  }, []);

  const defaultRequest = () => {
    const initData = defaultForm(0, stations);
    setState(initData);
    onFinish(initData);
  };
  const changeDate = (v) => {
    setState({ date: v });
  };

  const onFinish = async () => {
    fetchData(state);
  };

  const onReset = () => {
    defaultRequest();
  };

  const changeSearchType = (v) => {
    const { columnsType, date, searchType } = defaultForm(v, stations);
    setState({ columnsType, date, searchType });
  };

  const _getDateSelectEl = (v) => {
    switch (v) {
      case 0:
        return (
          <>
            <DatePicker.RangePicker
              value={state.date}
              onChange={changeDate}
              style={{ width: 240 }}
              placeholder={['开始日期', '结束日期']}
              format={'YYYYMMDD'}
              separator="-"
            />
            <TjSelect
              value={state.columnsType}
              onChange={(columnsType) => setState({ columnsType })}
              style={{ width: 200 }}
              options={COLIMNSTYPEOPTION}
              showSearch
              mode="multiple"
              label="数据类型"
            />
          </>
        );
      case 1:
        return (
          <DatePicker
            style={{ width: 300 }}
            value={state.date}
            onChange={changeDate}
            picker="week"
          />
        );
      case 2:
        return (
          <DatePicker
            style={{ width: 300 }}
            value={state.date}
            onChange={changeDate}
            picker="month"
          />
        );
    }
  };

  // 筛选交易单元类型
  const onTypeChange = (val) => {
    setState({ stationIdList: [] });
    const _newGroup = [];
    stations.forEach((t) => {
      if (!val) {
        // 全部交易单元
        _newGroup.push(t);
      }
      if (t.type === val) {
        // 选中的交易单元
        _newGroup.push(t);
      }
    });
    setState({ stationIdList: _newGroup.map((t) => t.value), type: val });
    setFilterStations(_newGroup);
  };

  return (
    <>
      <Space size={16} wrap>
        <Select
          value={state.type}
          style={{ width: 200 }}
          options={TYPE_OPTIONS}
          placeholder="场站类型"
          showArrow={true}
          onChange={onTypeChange}
        />
        <TjSelect
          style={{ width: 200 }}
          value={state.stationIdList}
          options={filterStations}
          showSearch
          onChange={(stationIdList) => setState({ stationIdList })}
          mode="multiple"
          label="交易单元"
          disabled={!filterStations.length}
        />
        <TjSegmented value={state.searchType} onChange={changeSearchType} options={SEARCH_TYPE} />
        {_getDateSelectEl(state.searchType)}
        <Space size={16}>
          <Button style={{ width: 98, height: 32 }} type="primary" onClick={onFinish}>
            查询
          </Button>
          <Button style={{ width: 98, height: 32 }} ghost onClick={onReset}>
            重置
          </Button>
        </Space>
      </Space>
      <Space>
        <Button type="link" icon={<UploadOutlined />} onClick={onExport}>
          导出
        </Button>
      </Space>
    </>
  );
};
